from flask import Flask  # 导入Flask模块
from flask import render_template #导入模板函数
import threading,time
from flask import request, redirect, url_for, jsonify
from services.data import main, write_db
from services import salary,xueli,jinyan
from database import db
from sqlalchemy import or_
import config#导入配置文件

app = Flask(__name__)#Flask初始化

app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config.from_object(config)#初始化配置文件
db.init_app(app)


from models.models import Data  # 导入 Data 模块
#创建表和字段


@app.route('/')
def first():
    return render_template("input.html")


@app.route('/list')#定义路由
def list(): # 定义list函数

    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 6, type=int)
    key = request.args.get('key', '')

    # 搜索过滤器
    data_query = Data.query.filter(or_(
        Data.titles.like(f"%{key}%"),
        Data.company.like(f"%{key}%"),
        Data.compScale.like(f"%{key}%"),
        Data.city.like(f"%{key}%"),
        Data.area.like(f"%{key}%"),
        Data.min_salary.like(f"{key}"),
        Data.max_salary.like(f"{key}"),
        Data.content_link.like(f"{key}")
    ))

    # 使用请求中的 `per_page` 参数调用 paginate
    data = data_query.paginate(page=page, per_page=per_page, error_out=False)

    return render_template("data.html", datas=data, key=key)


@app.route('/search')
def search():
    kw =request.args.get("kw")
    city =request.args.get("city")

    # 创建线程列表
    threads = []
    threads.append(threading.Thread(target=main, args=(kw, city, 1, 5)))  # 第一个线程爬前五页
    threads.append(threading.Thread(target=main, args=(kw, city, 6, 10)))  # 第二个线程爬后五页

    # 启动线程
    for thread in threads:
        try:
            thread.start()
        except:
            print("Error: 无法启动线程")

    # 等待所有线程完成
    for thread in threads:
        thread.join()  # 阻塞主线程，直到线程结束

    # 处理数据
    xz = salary.salary()
    xl = xueli.xuelifun()
    jy = jinyan.jinyanfun()
    return render_template('h.html', **locals())


#通过url传递信息
@app.route('/chart')
def charts():
    xz = salary.salary()
    xl = xueli.xuelifun()
    jy = jinyan.jinyanfun()
    return render_template('h.html',xz=xz,xl=xl,jy=jy)


#通过url传递信息
@app.route('/xinzi')
def xinzitest():
    a = salary.salary()
    print(a)
    return str(a)

@app.route('/xueli')
def xuelitest():
    data = xueli.xuelifun()
    print(data)
    return str(data)

@app.route('/insert_data', methods=['POST'])
def insert_data():
    try:
        # 获取表单数据
        data = [
            request.form['titles'],
            request.form['company'],
            request.form['compScale'],
            request.form['city'], 
            request.form['area'],
            request.form['min_salary'],
            request.form['max_salary'],
            request.form['date'],
            '不限', # degree
            '不限', # exper
            request.form['content_link']
        ]
        
        # 调用data.py中的write_db函数插入数据
        write_db(data)
        
        return jsonify({'success': True, 'message': '插入成功'})
    except Exception as e:
        print(f"插入数据失败: {str(e)}")
        return jsonify({'success': False, 'message': str(e)})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)





